import axios from 'axios';
import router from "@/router";
import {merchantHolderModuleServerSocket} from "../../public/config";
import {merchantCommoditiesModuleServerSocket} from "../../public/config";
import {merchantOrdersModuleServerSocket} from "../../public/config";
import {merchantMessagesModuleServerSocket} from "../../public/config";
import {merchantIndividualModuleServerSocket} from "../../public/config";
import {sharedFilesModuleServerSocket} from "../../public/config";

const services = {
    // 商家模块
    merchant: {
        holder: `http://${merchantHolderModuleServerSocket}`, // 置物格模块
        commodities: `http://${merchantCommoditiesModuleServerSocket}`, // 商品模块
        orders: `http://${merchantOrdersModuleServerSocket}`, // 订单模块
        messages: `http://${merchantMessagesModuleServerSocket}`, // 消息模块
        individual: `http://${merchantIndividualModuleServerSocket}`, // 用户模块
    },
    // 共有模块
    shared: {
        files: `http://${sharedFilesModuleServerSocket}` // 文件模块
    }
};

const request = axios.create({
    timeout: 30000
});

// 请求拦截器
request.interceptors.request.use(config => {
    const { url } = config;

    // 根据请求的 URL 动态设置 baseURL
    if (url.startsWith('/merchant/holder')){
        config.baseURL = services.merchant.holder;
    } else if (url.startsWith('/merchant/commodities') || url.startsWith('/merchant/toppings')) {
        config.baseURL = services.merchant.commodities;
    } else if (url.startsWith('/merchant/orders')) {
        config.baseURL = services.merchant.orders;
    } else if (url.startsWith('/merchant/messages')) {
        config.baseURL = services.merchant.messages;
    } else if (url.startsWith('/merchant/individual')) {
        config.baseURL = services.merchant.individual;
    } else if (url.startsWith('/shared/files')) {
        config.baseURL = services.shared.files;
    }

    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    let individual = localStorage.getItem("individual") ? JSON.parse(localStorage.getItem("individual")) : null;
    if (individual) {
        config.headers['token'] = individual.token; // 设置请求头
        if (individual.token) {
            config.headers.Authorization = 'Bearer ' + localStorage.getItem("token");
        }
        console.log(config.headers['token']);
    }

    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截器
request.interceptors.response.use(
    response => {
        let res = response.data;
        if (response.config.responseType === 'blob') {
            return res;
        }
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res;
        }
        if (res.code === '401') {
            router.push("/login");
        }
        return res;
    },
    error => {
        console.log('err' + error); // for debug
        return Promise.reject(error);
    }
);

export default request;